using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace NAst.Common
{
    /// <summary>
    /// Change IE proxy
    /// </summary>
    [Netlet("IEProxy")]
    public class ChangeIEProxyNetlet : INetlet
    {
        private string _proxyWhenEnabled = null;
        private string _proxyAutoConfig = null;
        private string _proxyOverride = null;
        private string _oldProxy = null;
        private string _oldProxyAutoConfig = null;
        private string _oldProxyOverride = null;
        private bool _oldProxyWasEnabled = false;
        private bool _wasChanged = false;

        #region INetlet Members

        public void Initialize(string stateName, System.Xml.XmlElement config)
        {
            _proxyWhenEnabled = config.GetAttribute("proxy");
            _proxyAutoConfig = config.GetAttribute("autoproxy");
            _proxyOverride = config.GetAttribute("override");
            string temp = config.GetAttribute("disable");
            if(string.IsNullOrEmpty(temp))
                return;
            if (temp.Equals("yes", StringComparison.InvariantCulture) ||
                temp.Equals("true", StringComparison.InvariantCulture))
            {
                _proxyWhenEnabled = null;
            }
        }

        public void Connect()
        {
            RegUtils _regUtils = new RegUtils();
            RegistryKey k = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            if (k != null)
            {
                _oldProxy = k.GetValue("ProxyServer", "") as string;
                _oldProxyAutoConfig = k.GetValue("AutoConfigURL", "") as string;
                Int32 temp = (Int32) k.GetValue("ProxyEnable", 0);
                _oldProxyOverride = k.GetValue("ProxyOverride", "") as string;
                _oldProxyWasEnabled = temp == 1;

                if (!string.IsNullOrEmpty(_proxyWhenEnabled))
                {
                    System.Diagnostics.EventLog.WriteEntry("NetworkAssitant", "Changing IEProxy configuration...", System.Diagnostics.EventLogEntryType.Information);
                    _wasChanged = true;

                    string szValue = string.Empty;
                    string szRegKey = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
                    byte[] abValue;
                    szValue = k.GetValue("ProxyServer").ToString();

                    k.SetValue("ProxyEnable", 1);
                    k.SetValue("ProxyServer", _proxyWhenEnabled);
                    k.SetValue("ProxyOverride", _proxyOverride);

                    if (_proxyAutoConfig.Length > 0)
                    {
                        k.SetValue("AutoConfigURL", _proxyAutoConfig);
                        k.SetValue("ProxyEnable", 0);
                    }

                    string aaValue = String.Empty;
                    szRegKey = szRegKey + @"\Connections";
                    _regUtils.GetKeyValue(RegUtils.RegKeyType.CurrentUser, szRegKey,
                                           "DefaultConnectionSettings", out abValue);
                    abValue[8] = 3;
                    aaValue = System.Text.Encoding.Default.GetString(abValue);
                    _regUtils.SetKeyValue(RegUtils.RegKeyType.CurrentUser, szRegKey,
                                          "DefaultConnectionSettings",
                                          Encoding.ASCII.GetBytes(aaValue.Replace(szValue, _proxyWhenEnabled)));
                }
                else
                {
                    _wasChanged = true;
                    k.SetValue("ProxyEnable", 0);
                    k.SetValue("ProxyServer", "");
                    k.SetValue("ProxyOverride", "");
                    k.SetValue("AutoConfigURL", "");
                    byte[] abValue;
                    string szRegKey = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections";
                    _regUtils.GetKeyValue(RegUtils.RegKeyType.CurrentUser, szRegKey,
                                          "DefaultConnectionSettings", out abValue);

                    abValue[8] = 1;
                    _regUtils.SetKeyValue(RegUtils.RegKeyType.CurrentUser, 
                                 szRegKey, "DefaultConnectionSettings", abValue);

                }
                k.Flush();
                k.Close();
            }
        }

        public void Disconnect()
        {
            if (!_wasChanged)
                return;
            RegistryKey k = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            if (k != null)
            {
                k.SetValue("ProxyEnable", _oldProxyWasEnabled?1:0);
                k.SetValue("ProxyServer", _oldProxy);
                k.SetValue("AutoConfigURL", _oldProxyAutoConfig);
                k.SetValue("ProxyOverride", _oldProxyOverride);
                k.Flush();
                k.Close();
            }

        }

        public void SaveState(System.Xml.XmlElement elmToSaveTo)
        {
            elmToSaveTo.SetAttribute("newProxy", _proxyWhenEnabled);
            elmToSaveTo.SetAttribute("oldProxy", _oldProxy);
            elmToSaveTo.SetAttribute("oldProxyWasEnabled", _oldProxyWasEnabled.ToString());
            elmToSaveTo.SetAttribute("oldAutoConfigURL", _oldProxyAutoConfig);
            elmToSaveTo.SetAttribute("oldProxyOverride", _oldProxyOverride);
            elmToSaveTo.SetAttribute("wasChanged", _wasChanged.ToString());
        }

        public void LoadState(System.Xml.XmlElement elmToLoadFrom)
        {
            _proxyWhenEnabled = elmToLoadFrom.GetAttribute("newProxy");
            _oldProxy = elmToLoadFrom.GetAttribute("oldProxy");
            _oldProxyAutoConfig = elmToLoadFrom.GetAttribute("oldAutoConfigURL");
            _oldProxyOverride = elmToLoadFrom.GetAttribute("oldProxyOverride");
            _wasChanged = false;
            _oldProxyWasEnabled = false;
            bool.TryParse(elmToLoadFrom.GetAttribute("oldProxyWasEnabled"), out _oldProxyWasEnabled);
            bool.TryParse(elmToLoadFrom.GetAttribute("wasChanged"), out _wasChanged);
        }

        #endregion
    }
}
